package com.ywb.edugui.utils;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author ywb
 * 字体工具类,调用registerFont方法默认会加载本系统使用的思源黑体，传入路径参数可加载路径参数的字体,然后使用map方法取出
 */
public class FontUtils {
    public static Map<String, Font> fontMap = new HashMap<>();
    public static void registerFont(){
        try{
            String fontPath = FontUtils.class.getResource("/fonts/思源黑体.ttf").toString();
            fontPath = URLDecoder.decode(fontPath, "utf-8");
            registerFont(fontPath.substring(5));
//            registerFont("D:\\Program Files\\CodeProject\\javaprojects\\edugui\\target\\classes\\fonts\\思源黑体.ttf");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void registerFont(String fontPath){
        try {
            Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(13f);
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ge.registerFont(customFont);
            fontMap.put(fontPath.substring(fontPath.lastIndexOf("/") + 1, fontPath.lastIndexOf(".")), customFont);
        } catch (IOException e) {
            e.printStackTrace();
        } catch(FontFormatException e) {
            e.printStackTrace();
        }
    }
    public static Font getFont(String fontName){
        return fontMap.get(fontName);
    }
    public static void changeFont(){
        //        使用FontUtils注册思源黑体,并使用SwingUIManager修改默认字体
        registerFont();
        Font font = fontMap.get("思源黑体");
        java.util.Enumeration keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof javax.swing.plaf.FontUIResource) {
                UIManager.put(key, font);
            }
        }
    }
}
